package com.android.base.okhttp.okUtil;

import android.content.Context;

import com.android.base.okhttp.okUtil.base.NetBean;
import com.android.base.okhttp.okUtil.callback.FileBack;
import com.android.base.okhttp.okUtil.callback.GsonBaseBack;
import com.android.base.tools.EmptyUtil;

import com.orhanobut.logger.Logger;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by Sammie on 2017/9/26.
 */

public class Execute {

    protected Request.Builder requestBuilder;
    protected OkHttpClient client;
    protected Context mContext;
    private  Call mCall = null;

    public Execute(Context context, Request.Builder request, OkHttpClient _client) {
        this.requestBuilder = request;
        this.client = _client;
        this.mContext = context;
    }

    /**
     * ****************************callBack请求封装****************************************
     */
    //统一对requestBuild处理，
    private Request getRequestBuild() {
        return requestBuilder.build();
    }


    //正常json返回的时候使用
    public Execute execute(GsonBaseBack call) {
        if (EmptyUtil.check(call)) throw new NullPointerException("回调：RxCall == null");
        call.setContext(mContext);
        mCall = client.newCall(getRequestBuild());
        mCall.enqueue(call);
        return this;
    }
    //下载文件时使用
    public Execute execute(FileBack fileBack) {
        if (EmptyUtil.check(fileBack)) throw new NullPointerException("回调：RxCall == null");
        fileBack.setContext(mContext);
        Call mCall = client.newCall(getRequestBuild());
        mCall.enqueue(fileBack);
        return this;
    }

    public void cancel(){
        if(mCall != null && !mCall.isCanceled()){
            mCall.cancel();
        }
    }

}
